<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>过滤器</title>
<link rel="stylesheet" href="${baseURL}/themes/default/css/filter.css" />
<link rel="stylesheet"
	href="${baseURL}/js/mCustomScrollbar/jquery.mCustomScrollbar.css" />
<script
	src="${baseURL}/js/mCustomScrollbar/jquery.mCustomScrollbar.concat.min.js"></script>
<script src="${baseURL}/js/handlebars/handlebars-min.js"></script>
</head>

<style>

</style>

<body>
	<div class="filter-bar">
		<!-- 过滤器 -->
		<div id="my-filter">
			我的筛选：<span id="currentFilter"></span>
		</div>

		<!-- 保存 -->
		<div class="top-filter">
			<div class="save-filter-btn">
				<a>保存过滤器</a>
			</div>
		</div>

		<!-- 更多 -->
		<div class="more-filter">
			<div class="more-condition">
				更多筛选条件 <i class="fa fa-caret-down"></i> <i class="fa fa-caret-up"></i>
				<div class="more">
					<div id="filter_list_more">
						<ul class="more-filter-content"></ul>
					</div>
					<div class="my-filter">
						<i class="fa fa-filter"></i><span>过滤器管理</span>
					</div>
				</div>
			</div>
		</div>
	</div>

	<!-- 保存过滤器 -->
	<div class="modal fade" id="saveFilterModal" tabindex="-1"
		role="dialog" aria-labelledby="editCheckLabel" aria-hidden="true">
		<div class="modal-dialog" style="width: 400px;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">×</button>
					<p class="modal-title" id="editCheckLabel">保存过滤器</p>
				</div>
				<div class="modal-body cont-table">
					<input id="filter_name_input"
						style="position: relative; bottom: auto; left: auto;" type="text"
						name="filterName" maxlength="28" placeholder="请输入过滤器名称" />
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-blue" id="saveFilter">
						保存</button>
					<button type="button" class="btn btn-gray" data-dismiss="modal"
						id="closeBtn">关闭</button>
				</div>
			</div>
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->

	<div class="modal fade" id="confirmFilterModal" tabindex="-1"
		role="dialog" aria-labelledby="editCheckLabel" aria-hidden="true">
		<div class="modal-dialog" style="width: 500px;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">×</button>
					<p class="modal-title" id="editCheckLabel">保存过滤器</p>
				</div>
				<div class="modal-body cont-table">
					<div style="position: relative;">
						<i
							style="font-size: 50px; position: absolute; top: 10px; left: 10px; color: #66ccff;"
							class="fa fa-exclamation-circle" aria-hidden="true"></i> <span
							style="position: absolute; left: 69px; top: 14px; font-size: 16px; color: #8B8878;">亲，您是否要更新过滤器或者另外再创建一个过滤器</span>
					</div>
				</div>
				<div class="modal-footer" style="margin-top: 50px;">
					<button type="button" class="btn btn-blue" id="updateFilter">
						保存</button>
					<button type="button" class="btn btn-blue" id="otherSaveFilter">
						另存</button>
					<button type="button" class="btn btn-gray" data-dismiss="modal"
						id="closeBtn">关闭</button>
				</div>
			</div>
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->

	<div class="modal fade" id="shareModal" tabindex="-1" role="dialog"
		aria-labelledby="editCheckLabel" aria-hidden="true">
		<div class="modal-dialog" style="width: 800px;">
			<div class="modal-content"></div>
		</div>
	</div>

	<script id="system-filter" type="text/x-handlebars-template">
		<div id="{{id}}" class="filter" state="{{state}}"><a title="{{name}}">{{name}}</a></div>
	</script>
	<script id="user-filter" type="text/x-handlebars-template">
		<div id="{{id}}" class="filter" state="{{state}}">
			<a title="{{name}}">{{name}}</a>
			<i title="删除过滤器【{{name}}】" class="fa fa-times-circle"></i>
			<i data-toggle="modal" href="${baseURL}/filter/filter/mdfilteredit/shareFilter.do?mdCode=${param.mdCode}&mdId=${param.mdId}&id={{id}}&isBootstrap=true" 
				data-target="#shareModal" title="分享过滤器【{{name}}】" class="fa fa-share"></i>
		</div>
	</script>
	<script type="text/javascript">
		var saveFilterBtn = $('.save-filter-btn');
		var topFilter = $('.top-filter');
		var moreFilterContent = $('.more-filter-content');
		var systemFilter = Handlebars.compile($('#system-filter').html());
		var userFilter = Handlebars.compile($('#user-filter').html());
		var filterArr = {};

		$(function() {
			$("#filter_list_more").mCustomScrollbar({
				axis : "yx",
				theme : "minimal-dark",
				scrollbarPosition : "outside"
			});

			// 保存按钮
			$('.save-filter-btn').click(function() {
				saveFilter();
			});

			// 过滤器
			$('.filter-bar').on('click', '.filter>a', function() {
				var filterDiv = $(this).parent();
				var id = filterDiv.attr('id');

				var currentFilter = $(".current-filter");
				if (currentFilter.length > 0 && currentFilter.attr("id") != id ) {
					currentFilter.show();
					currentFilter.removeClass("current-filter");
				}else if(currentFilter.attr("id") == id){
					currentFilter.removeClass("current-filter");
					setCurrentFilter();
					renderSelectorByFilter(null);
				}else{
					setCurrentFilter(id);
					renderSelectorByFilter(filterArr[id].content);
				}
			});

			// 删除按钮
			$('.filter-bar').on('click', '.filter .fa-times-circle',
					function() {
 						var filterDiv = $(this).parent();
						var id = filterDiv.attr('id');
						var filterName = $(this).prevAll('a').attr('title');
						deleteFilter(id, filterName);
					});

			// 分享按钮
			/* $('.filter-bar').on('click', '.filter .fa-share', function(){
				shareFilter($(this).parent().attr('id'));
			}); */

			$('.my-filter')
					.click(
							function() {
								parent
										.f_addTab(
												'myFilter',
												'我的过滤器',
												'${baseURL}/jdbc/common/basecommonlist/list.do?mdCode=filter&defaultParams={"userId":"currentUserId()"}');
							});

			loadFilter();
		});

		/*
		 * 通过过滤器加载数据
		 */
		function renderSelectorByFilter(content) {
			if(content == null)
				selector.resetSelector();
			else{
				selector.resetSelector();
				var condition = eval('(' + content + ')');
				for (c in condition) {
					selector.setSelectorValue(condition[c].name,
							condition[c].value, null);
				}
			}
			
			selector.search();
		}

		/*
		 * 加载过滤器数据
		 */
		function loadFilter() {
			$
					.ajax({
						url : '${baseURL}/filter/filter/mdfilterlist/loadFilterJson.do',
						type : 'post',
						data : {
							"mdCode" : '${param.mdCode}',
							"mdId" : "${param.mdId}"
						},
						dataType : 'json',
						success : function(data) {
							if (data && data.Rows) {
								setFilterToPage(data.Rows);
								flushFilterCount(data.Rows);
							}
						}
					});
		}

		/*
		 * 刷新过滤器计数
		 */
		function flushFilterCount() {
			$(".top-filter>.filter").each(function () {
                filterCount($(this).attr("id"))
			});
		}

        function filterCount(filterId) {
            var e = filterArr[filterId];
            $.ajax({
				url : '${baseURL}/jdbc/common/basecommonlist/filterCount.do',
				type : 'post',
				data : {
					searchParam : e.content,
					mdId : '${param.mdId}',
					mdCode : '${param.mdCode}'
				},
				dataType : 'json',
				success : function(data) {
					if (data && data.count) {
						var $filter = $("#" + e.id
							+ ">a");
						$filter.text($filter
								.attr("title")
							+ "("
							+ data.count
							+ ")");
					}
				}
			});
        }

		/*
		 * 将过滤器设置到页面上
		 */
		function setFilterToPage(rows) {
			saveFilterBtn.prevAll().remove();
			moreFilterContent.children().remove();

			var isTop = true;
			$.each(rows, function(i, e) {
				isTop = renderFilter(e, isTop);
			});
		}

		function renderFilter(e, isTop) {
			var template = e.state == 0 ? systemFilter : userFilter;
			var html = template(e);
			if (isTop && isTopFilter(html)) {
				saveFilterBtn.before(html);
			} else {
				var li = $("<li></li>");
				li.append(html);
				moreFilterContent.append(li);
				isTop = false;
			}
			filterArr[e.id] = e;
			return isTop;
		}

		/*
		 * 判断过滤器是放在顶部还是放在更多那里
		 */
		function isTopFilter(html) {
			var isTop = false;
			var filter = typeof html == 'string' ? $(html) : html;
			filter.attr('visibility', 'hidden');
			topFilter.append(filter);
			var moreFilterLeft = $('.more-filter').offset().left;
			var topFilterRight = topFilter.offset().left + topFilter.width();
			if (topFilterRight < moreFilterLeft) {
				isTop = true;
			}
			filter.remove();
			return isTop;
		}

		/*
		 * 保存过滤器弹出框
		 */
		function saveFilter() {
			if ($(".current-filter").length > 0) {
				updateDialog();
			} else {
				createDialog();
			}
		}

		/*
		 * 输入过滤器名的弹出框
		 */
		function createDialog() {
			$("#filter_name_input").val("");
			$('#saveFilterModal').modal();
			$("#filter_name_input").focus();
		}

		/*
		 * 更新过滤器的弹出框
		 */
		function updateDialog() {
			$('#confirmFilterModal').modal();
		}

		$("#updateFilter").click(function() {
			if ($(".current-filter").attr('state') == 0) {
				win.$.ligerDialog.warn('亲，不能更新固定过滤器哦！');
				return false;
			}
			var content = JSON.stringify(selector.getSelectorValue());
			saveFileter({
				id : $(".current-filter").attr("id"),
				content : content
			}, function() {
				$('#confirmFilterModal').modal('hide');
			});
		});

		$("#otherSaveFilter").click(function() {
			$('#confirmFilterModal').modal('hide');
			createDialog();
		})

		$("#saveFilter").click(function() {
			var content = JSON.stringify(selector.getSelectorValue());
			var name = $('#filter_name_input').val();
			if (!name || name == '') {
				win.$.ligerDialog.warn('请输入过滤器名');
				return;
			}
			if (name.length > 28) {
				win.$.ligerDialog.warn('过滤器长度不能超过28个字符');
				return;
			}
			var params = new Object();
			params.name = name;
			params.content = content;
			params.mdCode = '${param.mdCode}';
			params.mdId = '${param.mdId}';
			params.pageUri = getPageUri();
			saveFileter(params, function() {
 				$('#saveFilterModal').modal("hide");
			});
		})

		/*
		 * 保存过滤器
		 */
		var isSave = true;
		function saveFileter(params, callback) {
			// 防止重复提交
			if (isSave) {
				isSave = false;
				$.ajax({
					url : '${baseURL}/filter/filter/mdfiltersave/saveFilter.do',
					type : 'post',
					data : params,
					dataType : 'json',
					success : function(data) {
						if (data.hasOk) {
							// 没有id为新增，把新添加的过滤器渲染到页面上
							if(!params.id) {
								renderFilter(data.bean, true);
                                filterCount(data.bean.id);
							} else {
							    // 修改时，更新页面上存储的过滤器内容
								filterArr[params.id].content = data.bean.content;
							}
							BT.showSuccess(data.message);
							if (callback) {
								callback();
							}
						} else {
						    BT.showError(data.message);
						}
					},
					complete : function() {
						isSave = true;
					}
				});
			}
		}

		/*
		 * 删除过滤器
		 */
		function deleteFilter(id, name) {
			if (!id || id == '') {
				return false;
			}
			var currentFilter = $(".current-filter");
 			if (currentFilter != null && currentFilter.attr('id') == id) {
				win.$.ligerDialog.warn('亲，正在使用的过滤器不能删除哦');
				return false;
			}

			win.$.ligerDialog
					.confirm(
							'亲，确认要删除过滤器【' + name + '】吗?',
							'删除确认',
							function(confirm) {
								if (confirm) {
									$
											.ajax({
												url : '${baseURL}/filter/filter/mdfilterdelete/delete.do',
												type : 'post',
												dataType : "json",
												data : "ids=" + id,
												success : function(msg) {
													if (msg && msg.hasOk) {
														if ($('#' + id).parent(
																"li").length > 0) {
															$('#' + id).parent(
																	"li")
																	.remove();
														} else {
															$('#' + id)
																	.remove();
															var mfilter = $(".more-filter-content .filter:first");
															if (mfilter) {
																renderFilter(
																		filterArr[mfilter
																				.attr('id')],
																		true);
																$(
																		".more-filter-content>li:first")
																		.remove();
															}
														}
														win.$.ligerDialog
																.success('已删除过滤器【'
																		+ name
																		+ '】');
													} else {
														win.$.ligerDialog
																.error("操作失败!失败信息如下:\n"
																		+ msg.message
																		+ "\n如您对以上信息有疑问，请联系管理人员!");
													}
												}
											});
								}
							});
		}

		function hideShareModal() {
 			$('#shareModal').modal("hide");
		}

		function setCurrentFilter(filterId) {
			if(filterId == undefined)
				return;
			var currentFilter = null;
			if (filterId) {
				currentFilter = $("#" + filterId);
			} else {
				currentFilter = $(".top-filter>.filter:first");
			}
			if (currentFilter.length > 0) {
				var a = currentFilter.children('a');
				if (currentFilter.parent().hasClass('top-filter')) {
					currentFilter.addClass('current-filter');
					$('#currentFilter').html('');
					$('#currentFilter').removeAttr('title');
					$('#currentFilter').removeClass('show-current-filter');
				} else {
					currentFilter.hide();
					currentFilter.addClass('current-filter');
					$('#currentFilter').html(a.html());
					$('#currentFilter').attr('title',
							'当前使用的过滤器：' + a.attr('title'));
					$('#currentFilter').addClass('show-current-filter');
				}
			}
		}

		/*
		 * 获取当前页面uri
		 */
		function getPageUri() {
			var uri = window.location.pathname;
			var re = new RegExp('^' + baseURL);
			return uri.replace(re, '');
		}

		/*
		 * 屏幕宽度改变时，处理过滤器的显示位置 
		 */
		window.onresize = function() {
			if ($(window).width() < 350) {
				$('#my-filter').hide();
			} else {
				$('#my-filter').show();
			}
			var moreFilterLeft = $('.more-filter').offset().left;
			var topFilterRight = topFilter.offset().left + topFilter.width();
			if (topFilterRight > moreFilterLeft) {
				while (topFilterRight > moreFilterLeft) {
					var filter = saveFilterBtn.prev();
					if (filter.length == 0) {
						break;
					}
					if (filter.hasClass('current-filter')) {
						$('#currentFilter').html(filter.children('a').html());
						$('#currentFilter').attr(
								'title',
								'当前使用的过滤器：'
										+ filter.children('a').attr('title'));
						$('#currentFilter').addClass('show-current-filter');
					}
					var li = $('<li></li>');
					li.append(filter);
					moreFilterContent.prepend(li);
					if (filter.hasClass('current-filter')) {
						filter.hide();
					}
					topFilterRight = topFilter.offset().left
							+ topFilter.width();
				}
			} else if (topFilterRight < moreFilterLeft) {
				while (topFilterRight < moreFilterLeft) {
					var li = moreFilterContent.children(':first');
					if (li.length == 0) {
						break;
					}
					var filter = li.children(':first');
					if (filter.hasClass('current-filter')) {
						filter.show();
					}
					var filterId = filter.attr('id');

					var template = (filterArr[filterId].state == 0 ? systemFilter
							: userFilter);
					var html = template(filterArr[filterId]);
					if (isTopFilter(html)) {
						if (filter.hasClass('current-filter')) {
							$('#currentFilter').html('');
							$('#currentFilter').removeAttr('title');
							$('#currentFilter').removeClass(
									'show-current-filter');
							html = $(html);
							html.addClass('current-filter');
							currentFilter = html;
						}
						saveFilterBtn.before(html);
						li.remove();
					} else {
						if (filter.hasClass('current-filter')) {
							filter.hide();
						}
						break;
					}
					topFilterRight = topFilter.offset().left
							+ topFilter.width();
				}
			}
		}
	</script>
</body>
</html>